require 'cacheable'
require 'open-uri'
require 'rexml/document'

class Weather

  include Cacheable

  def initialize(rss)
    @rss = rss
  end

  def condition
    "Today's weather: #{forecast.attributes["text"]}, Hi: #{forecast.attributes["high"]}#{unit}, Lo: #{forecast.attributes["low"]}#{unit} (Currently #{current.attributes["text"]}, #{current.attributes["temp"]}#{unit})"
  end

  def photo
    download_photo!
    photo_path
  end

  private

  def feed
    REXML::Document.new(open(@rss).read)
  end

  def current; feed.elements.to_a("//yweather:condition")[0]; end
  def forecast; feed.elements.to_a("//yweather:forecast")[0]; end
  def unit; feed.elements["//yweather:units"].attributes["temperature"]; end
  def photo_id; current.attributes["code"]; end
  def photo_url; "http://us.i1.yimg.com/us.yimg.com/i/us/we/52/#{photo_id}.gif"; end
  def photo_path; "/tmp/yweather_img_#{photo_id}.gif"; end

  def download_photo!
    File.open(photo_path, "w+") { |f| f.write open(photo_url).read } unless File.exists?(photo_path)
  end

  caches :condition, :for => 15.minutes
  caches :feed, :for => 15.minutes
  caches :photo, :for => 15.minutes

end
